const express=require("express");
const util=require("../utils/utils")
const { db } =require("../db/db")
const router=express.Router()

// 读取首页
router.get("/", async(req,res)=>{
    let data=await util.read('pages/index.html');
    res.end(data)
});
// 读取登录页
router.get("/logins", async(req,res)=>{
    let data=await util.read('pages/login.html');
    res.end(data)
})
// 查询数据库
router.get("/getUser",(req,res)=>{
    const sql="select * from user"
    db(sql,null).then(data=>{
        res.send(data)
    })
})
// 添加数据库
router.post("/addUser",(req,res)=>{
    const sql="insert into user set ?"
    const sqlParams=req.body
    db(sql,sqlParams).then((data)=>{
        res.send({
            code:200,
            msg:"添加成功"
        })
    })
})
// 修改
router.post("/updUser",(req,res)=>{
    const sql=`update user set ? where id=${req.body.id}`
    const sqlParams=req.body
    db(sql,sqlParams).then((data)=>{
        res.send({
            code:200,
            msg:"修改成功"
        })
    })
})
// 删除
router.post("/delUser",(req,res)=>{
    const sql=`delete from user where id=${req.body.id}`
    db(sql,null).then((data)=>{
        res.send({
            code:200,
            msg:"删除成功"
        })
    })
})
// 按Id查询
router.get("/getUserById",(req,res)=>{
    const sql=`select * from user where id=${req.body.id}`
    db(sql,null).then(data=>{
        res.send(data)
    })
})
// 登录
router.get("/login",(req,res)=>{
    const sql="select username,password from user where username = '"+req.body.username+"' and password = '"+req.body.password+"'"
    db(sql,null).then(data=>{
        if(data.length>0){
           res.send({
               code:200,
               msg:"登录成功"
           })
        }else{
            res.send({
                code:500,
                msg:"用户名和密码不正确！请检查后重新输入"
            })
        }
    })
})
// 注册
router.post("/register",(req,res)=>{
    const sql="select username from user where username = '"+req.body.username+"'"
    db(sql,null).then(data=>{
        if(data.length>0){
            res.send({
                code:500,
                msg:"用户名已存在，请重新输入"
            })
        }else{
            const sql="insert into user set ?"
            const sqlParams=req.body
            db(sql,sqlParams).then((data)=>{
                res.send({
                    code:200,
                    msg:"注册成功"
                })
            })
        }
    })
})

module.exports=router;